import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout,
                             QPushButton, QLineEdit, QVBoxLayout, QFileDialog, QMessageBox)
from PyQt5.QtCore import Qt
import requests


class CvvQT(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("manatee")
        self.setGeometry(300, 300, 800, 800)

        # 创建主布局
        main_layout = QVBoxLayout()

        # 创建显示框
        self.display = QLineEdit('0')
        self.display.setReadOnly(True)
        main_layout.addWidget(self.display)

        # 创建上传按钮
        self.upload_btn = QPushButton("上传txt文件")
        self.upload_btn.clicked.connect(self.upload_file)
        main_layout.addWidget(self.upload_btn)

        # 设置布局
        self.setLayout(main_layout)

    def upload_file(self):
        """上传txt文件的函数"""
        try:
            # 打开文件选择对话框
            file_path, _ = QFileDialog.getOpenFileName(
                self,
                "选择txt文件",
                "",
                "Text Files (*.txt);;All Files (*)"
            )

            if file_path:
                self.display.setText(f"已选择文件: {file_path}")

                # 这里调用上传接口
                result = self.call_upload_api(file_path)

                if result:
                    QMessageBox.information(self, "成功", "文件上传成功！")
                else:
                    QMessageBox.warning(self, "失败", "文件上传失败！")

        except Exception as e:
            QMessageBox.critical(self, "错误", f"上传过程中出现错误: {str(e)}")

    def call_upload_api(self, file_path):
        """调用上传接口的函数
        你需要根据实际的API接口修改这个函数
        """
        try:
            # 示例：使用requests上传文件
            # 请根据你的实际API接口修改下面的代码

            # 假设你的接口地址是 http://example.com/upload
            url = "http://example.com/upload"  # 请替换为实际接口地址

            # 打开文件
            with open(file_path, 'rb') as f:
                files = {'file': (file_path.split('/')[-1], f, 'text/plain')}

                # 发送POST请求
                response = requests.post(url, files=files)

                # 检查响应状态
                if response.status_code == 200:
                    print("上传成功")
                    print("服务器响应:", response.text)
                    return True
                else:
                    print(f"上传失败，状态码: {response.status_code}")
                    return False

        except requests.exceptions.RequestException as e:
            print(f"网络请求错误: {e}")
            return False
        except Exception as e:
            print(f"其他错误: {e}")
            return False


if __name__ == '__main__':
    app = QApplication(sys.argv)
    calc = CvvQT()
    calc.show()
    sys.exit(app.exec_())